package com.fh.modules.system.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.fh.common.components.redis.RedisActor;
import com.fh.common.constant.ActionLogResult;
import com.fh.common.constant.CommonConstant;
import com.fh.common.exception.Assert;
import com.fh.common.system.api.ISysBaseAPI;
import com.fh.common.util.PasswordUtil;
import com.fh.modules.shiro.authc.util.JwtUtil;
import com.fh.modules.system.entity.SysUser;
import com.fh.modules.system.model.SysLoginModel;
import com.fh.modules.system.service.ISysLogService;
import com.fh.modules.system.service.ISysLoginService;
import com.fh.modules.system.service.ISysUserService;
import com.fh.modules.system.vo.LoginVO;

/**
 * @author Qiu,Junda 
 * @date 2019年6月26日
 * @description 登录接口实现类
 */
@Service
public class SysLoginServiceImpl implements ISysLoginService{
	@Autowired
	private ISysUserService sysUserService;
	@Autowired
	private ISysBaseAPI sysBaseAPI;
	@Autowired
    private RedisActor redisActor;
	@Autowired
	private ISysLogService logService;
	@Override
	public LoginVO login(SysLoginModel sysLoginModel) {
		LoginVO loginVo=new LoginVO();
		String username = sysLoginModel.getUsername();
		String password = sysLoginModel.getPassword();
		SysUser sysUser = sysUserService.getUserByName(username);
		if(sysUser==null) {
			String logresult="登录失败，用户不存在！";
			sysBaseAPI.addLog(logresult, CommonConstant.LOG_TYPE_LOGIN, null,ActionLogResult.FAIL,logresult);
			Assert.error(logresult);
		}else {
			//密码验证
			String userpassword = PasswordUtil.encrypt(username, password, sysUser.getSalt());
			String syspassword = sysUser.getPassword();
			if(!syspassword.equals(userpassword)) {
				String logresult="登录失败，密码错误";
				sysBaseAPI.addLog(logresult, CommonConstant.LOG_TYPE_LOGIN, null,ActionLogResult.FAIL,logresult);
				Assert.error(logresult);
			}
			//生成token
			String token = JwtUtil.sign(sysUser.getId(), syspassword);
			redisActor.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
			 //设置超时时间
			redisActor.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME/1000);
			
			JSONObject obj = new JSONObject();
			obj.put("token", token);
			obj.put("userInfo", sysUser);
			loginVo.setResult(obj);
			loginVo.success("登录成功");
			sysBaseAPI.addLog(username,"用户名: "+username+",登录成功！", CommonConstant.LOG_TYPE_LOGIN, null,ActionLogResult.SUCCESS,"success");
		}
		return loginVo;
	}
	

}
